package com.ssyt.yt1.day29.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Scanner;

public class TuringRobotDemo {

	public static void main(String[] args) {
		Scanner scanner = null;
		InputStream inputStream = null;
		BufferedReader br = null;
		try {
			scanner = new Scanner(System.in);
			while (true) {
				System.out.println("请输入信息：");
				String info = URLEncoder.encode(scanner.nextLine(), "utf-8");
				URL url = new URL(
						"http://www.tuling123.com/openapi/api?key=a5484371e97ca24cd4199f5c526o799c&info="
								+ info);
				HttpURLConnection httpURLConnection = (HttpURLConnection) url
						.openConnection();
				httpURLConnection.setConnectTimeout(3000);
				if (httpURLConnection.getResponseCode() == 200) {
					inputStream = httpURLConnection.getInputStream();
					br = new BufferedReader(new InputStreamReader(inputStream));
					StringBuilder sb = new StringBuilder();
					String str = null;
					while ((str = br.readLine()) != null) {
						sb.append(str);
					}
					String result = sb.toString();
					result = result.substring(result.lastIndexOf("\":\"") + 3,
							result.lastIndexOf("\"}"));
					System.out.println(result);
				} else {
					System.out.println("访问失败~");
				}
			}
		} catch (SocketTimeoutException e) {
			System.out.println("连接超时~");
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (scanner != null) {
				scanner.close();
			}
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
